package com.lagou.server.service.dto;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

/**
 * RPC解码类
 * @author yzh
 */
public class RpcDecoder extends ByteToMessageDecoder {

    /**
     * 要解码的类的字节码对象
     */
    private Class<?> clazz;

    /**
     * 序列化对象
     */
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    /**
     * 解码的方法
     * @param channelHandlerContext
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (clazz != null && byteBuf != null && byteBuf.readableBytes() >= 4) {
            int dataLength = byteBuf.readInt();
            byte[] bytes = new byte[dataLength];
            bytes = ByteBufUtil.getBytes(byteBuf, 4, dataLength);
            Object object = serializer.deserialize(clazz, bytes);
            list.add(object);
            byteBuf.skipBytes(byteBuf.readableBytes());
        }
    }

}
